package com.example.demo.dao.impl;

import com.example.demo.dao.BaseDaoImpl;
import com.example.demo.dao.IAddressDao;
import com.example.demo.model.po.AddressPage;
import com.example.demo.model.request.AddressPageRequest;
import com.example.demo.model.request.VpsPageRequest;
import com.example.demo.util.AssertUtils;
import com.example.demo.util.DateUtils;
import org.jooq.Condition;
import org.jooq.Record;
import org.jooq.SelectJoinStep;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

import static com.example.demo.jooq.tables.Address.ADDRESS;
import static org.jooq.impl.DSL.count;

@Component
public class IAddressDaoImpl extends BaseDaoImpl implements IAddressDao {


    @Override
    public List<AddressPage> queryPageAddressList(AddressPageRequest addressPageRequest) {
        //查询条件
        List<Condition> conditions = new ArrayList<>();
        if(AssertUtils.isNotEmpty(addressPageRequest.getKeyword())){
            conditions.add(ADDRESS.COUNTRY.likeRegex(addressPageRequest.getKeyword().trim())
                            .or(ADDRESS.NAME.likeRegex(addressPageRequest.getKeyword().trim()))
                            .or(ADDRESS.PHONE.likeRegex(addressPageRequest.getKeyword().trim()))
            );
        }
        if(AssertUtils.isNotEmpty(addressPageRequest.getAddressStatus())){
            conditions.add(ADDRESS.ADDRESS_STATUS.eq(addressPageRequest.getAddressStatus()));
        }
        if(AssertUtils.isNotEmpty(addressPageRequest.getCreatedDate())){
            conditions.add(ADDRESS.CREATED_DATE.eq(DateUtils.stringToTime(addressPageRequest.getCreatedDate())));
        }
        if(AssertUtils.isNotEmpty(addressPageRequest.getSite())){
            conditions.add(ADDRESS.SITE.eq(addressPageRequest.getSite()));
        }
        SelectJoinStep<Record> totalLine = this.getDslContext()
                .select(ADDRESS.fields())
                .select(count().over().as("totalLine"))
                .from(ADDRESS);
        totalLine.where(conditions);
        return totalLine.orderBy(ADDRESS.CREATED_DATE.desc())
                .offset(addressPageRequest.getOffset())
                .limit(addressPageRequest.getPageSize())
                .fetchInto(AddressPage.class);
    }
}
